package br.com.dbsti.tabela;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import org.apache.commons.beanutils.PropertyUtils;

public class CustomTableModel<T> implements TableModel {
    
    public List<T> dados;
    public String[] nomeColunas;
    public String[] propriedades;
    public Class<T> classe;

    public CustomTableModel(List<T> dados, String[] nomeColunas, String[] propriedades, Class<T> classe) {
        this.dados = dados;
        this.nomeColunas = nomeColunas;
        this.propriedades = propriedades;
        this.classe = classe;
    }
    
    public int getRowCount() {
        return dados.size();
    }

    public int getColumnCount() {
        return nomeColunas.length;
    }

    public String getColumnName(int columnIndex) {
        return nomeColunas[columnIndex];
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }


    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        
    }

    public void addTableModelListener(TableModelListener l) {
        
    }

    public void removeTableModelListener(TableModelListener l) {
        
    }
    
    public Class<?> getColumnClass(int columnIndex) {
        try {
            return classe.getDeclaredField(propriedades[columnIndex]).getType();
        } catch (NoSuchFieldException ex) {
            return String.class;
        } catch (SecurityException ex) {
            return String.class;
        }
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        T objeto = dados.get(rowIndex);
        try {
            return PropertyUtils.getProperty(objeto, propriedades[columnIndex]);
        } catch (IllegalAccessException ex) {
            return "";
        } catch (InvocationTargetException ex) {
            return "";
        } catch (NoSuchMethodException ex) {
            return "";
        }
    }

}